﻿using agsXMPP;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SuperMessagerCenter
{
    public class Gtalk
    {
		XmppClientConnection talkConnection = new XmppClientConnection();

		public Gtalk()
		{
			this.Init();
		}

		void Init()
		{
			talkConnection.OnLogin += new ObjectHandler(xmppCon_OnLogin);
			talkConnection.OnRosterStart += new ObjectHandler(xmppCon_OnRosterStart);
			talkConnection.OnRosterEnd += new ObjectHandler(xmppCon_OnRosterEnd);
			talkConnection.OnRosterItem += new XmppClientConnection.RosterHandler(xmppCon_OnRosterItem);
			talkConnection.OnPresence += new agsXMPP.protocol.client.PresenceHandler(xmppCon_OnPresence);
			talkConnection.OnAuthError += new XmppElementHandler(xmppCon_OnAuthError);
			talkConnection.OnError += new ErrorHandler(xmppCon_OnError);
			talkConnection.OnClose += new ObjectHandler(xmppCon_OnClose);
			talkConnection.OnMessage += new agsXMPP.protocol.client.MessageHandler(xmppCon_OnMessage);
		}

		private void xmppCon_OnMessage(object sender, agsXMPP.protocol.client.Message msg)
		{
			// ignore empty messages (events)
			if (msg.Body == null)
				return;

			Console.WriteLine(String.Format("OnMessage from:{0} type:{1}", msg.From.Bare, msg.Type.ToString()));
			Console.WriteLine(msg.Body);
		}

		private void xmppCon_OnClose(object sender)
		{
			Console.WriteLine("xmppCon_OnClose");
		}

		private void xmppCon_OnError(object sender, Exception ex)
		{
			Console.WriteLine(ex.Message);
			Console.WriteLine(ex.Source);
			Console.WriteLine(ex.StackTrace);
		}

		private void xmppCon_OnAuthError(object sender, agsXMPP.Xml.Dom.Element e)
		{
			Console.WriteLine(e.ToString());
		}

		private void xmppCon_OnPresence(object sender, agsXMPP.protocol.client.Presence pres)
		{
			Console.WriteLine(pres.ToString());
		}

		private void xmppCon_OnRosterItem(object sender, agsXMPP.protocol.iq.roster.RosterItem item)
		{
			Console.WriteLine(item.ToString());
		}

		private void xmppCon_OnRosterEnd(object sender)
		{
			
		}

		private void xmppCon_OnRosterStart(object sender)
		{
			
		}

		private void xmppCon_OnLogin(object sender)
		{
			Console.WriteLine("xmppCon_OnLogin");
			Console.WriteLine(talkConnection.Status);
			agsXMPP.protocol.client.Message msg = new agsXMPP.protocol.client.Message();
			msg.Type = agsXMPP.protocol.client.MessageType.chat;
			msg.To = new Jid("qiuzhequn@gmail.com");
			msg.Body = "How";

			talkConnection.Send(msg);
		}

		public void Wait()
		{
			Jid jid = new Jid("qiuqikun@gmail.com");

			talkConnection.Username = jid.User;
			talkConnection.Server = jid.Server;
			talkConnection.Password = "qiuzhequn.19831028";
			talkConnection.AutoResolveConnectServer = true;

			talkConnection.Open();

		}
    }
}
